package com.nanfang51g3.ckz.ui.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.adapter.base.DividerItemDecoration;
import com.nanfang51g3.ckz.adapter.ext.IndexAdapter;
import com.nanfang51g3.ckz.adapter.listener.OnItemClickListener;
import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.domain.IndexBean;
import com.nanfang51g3.ckz.domain.RightTypeBean;
import com.nanfang51g3.ckz.event.PostTypeData;
import com.nanfang51g3.ckz.event.RefreshTypeData;
import com.nanfang51g3.ckz.event.RxBus;
import com.nanfang51g3.ckz.receiver.NetReceiver;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.fragment.base.BaseLazyLoadFragment;
import com.nanfang51g3.ckz.ui.index.DaggerIndexContractComponent;
import com.nanfang51g3.ckz.ui.index.IndexContract;
import com.nanfang51g3.ckz.ui.index.IndexPresenter;
import com.nanfang51g3.ckz.ui.index.IndexPresenterModule;
import com.nanfang51g3.ckz.ui.index.LocationServerListener;
import com.nanfang51g3.ckz.ui.share.ShareTuiActivity;
import com.nanfang51g3.ckz.utils.EasyToast;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.NetUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2016/5/18.
 */
public class HomeIndexFragment extends BaseLazyLoadFragment implements IndexContract.View, NetReceiver.NetEventHandle {
    IndexContract.IndexActionsListener indexActionsListener;
    IndexAdapter indexAdapter;
    ArrayList<IndexBean> releaseInfoS = new ArrayList<>();
    @Bind(R.id.index_recycler_view)
    RecyclerView indexRecyclerView;
    @Bind(R.id.index_ptr_frame)
    PtrClassicFrameLayout indexPtrFrame;
    @Bind(R.id.home_tv_title_city)
    TextView homeTvTitleCity;
    @Bind(R.id.home_iv_right)
    ImageView homeIvRight;
    boolean more = false;
    int page = 1;
    int limit = 10;
    String tName;

    @Override
    public IPresenter getPresenter() {
        return indexActionsListener;
    }

    @Override
    public void showProgress() {
        super.showPro(getActivity(), R.string.str_progress_index);
    }

    @Override
    public void dismissProgress() {
        super.dismissPro();

    }

    @OnClick(R.id.home_iv_right)
    public void index_iv_right(View view) {
        //发送
        RxBus.getDefault().post(new PostTypeData(0, null, true));
    }

    @Override
    public void showSuccess(List<IndexBean> remote, ArrayList<RightTypeBean> strings, boolean pullDown, String tName) {
        KLog.i("Evd", "showSuccess 1= " + remote.size());
        KLog.i("Evd", "showSuccess 2= " + releaseInfoS.size());
        this.tName = tName;
        firstNetwork = false;//第一次请求成功
        /**刷新数据*/
        if (pullDown) {
            KLog.i("Evd", "pullDown = " + pullDown + "-" + strings.size());
            RxBus.getDefault().post(new PostTypeData(1, strings, pullDown));
        }
        /**刷新侧滑*/
        if (tName != null) {
            KLog.i("Evd", "进入刷新侧滑 ");
            RxBus.getDefault().post(new PostTypeData(1, null, true));
        }
        if (more) {
            releaseInfoS.addAll(remote);
            indexAdapter.addList(releaseInfoS);
        } else {
            releaseInfoS.clear();
            releaseInfoS.addAll(remote);
            indexAdapter.addList(releaseInfoS);
        }
        KLog.i("Evd", "showSuccess 3= " + releaseInfoS.size());
    }

    @Override
    public void showLocationValue(final String city) {
        KLog.i("Evd", "位置改变：=" + city);
        KLog.i("Evd", homeTvTitleCity == null ? "indexTvTitleCity-1" : "indexTvTitleCity-0");
        if (homeTvTitleCity != null) {
            homeTvTitleCity.post(new Runnable() {
                @Override
                public void run() {
                    if (!TextUtils.isEmpty(city)) {
                        homeTvTitleCity.setVisibility(View.VISIBLE);
                        homeTvTitleCity.setText(city);
                    }
                }
            });
        }
    }

    //首次进入访问
    boolean firstNetwork = false;

    @Override
    public Context getContext() {
        return getActivity();
    }

    @Override
    public void showMessage(String message, String tName) {
        this.tName = tName;
        EasyToast.showShort(getActivity(), message);
        if (page > 0) { //如果是上拉加载则不操作侧滑
            RxBus.getDefault().post(new PostTypeData(1, null, true));
        }

    }

    @Override
    public void netState(NetReceiver.NetState netCode) {
        switch (netCode) {
            case NET_NO:
                KLog.e("JK", "没有网络连接");
                break;
            case NET_2G:
                if(firstNetwork){
                    indexActionsListener.requestIndex(page, limit, true);
                    indexPtrFrame.refreshComplete();
                }
                KLog.e("JK", "2g网络");
                break;
            case NET_3G:
                KLog.e("JK", "3g网络");
                if(firstNetwork){
                    indexActionsListener.requestIndex(page, limit, true);
                    indexPtrFrame.refreshComplete();
                }
                break;
            case NET_4G:
                KLog.e("JK", "4g网络");
                if(firstNetwork){
                    indexActionsListener.requestIndex(page, limit, true);
                    indexPtrFrame.refreshComplete();
                }
                break;
            case NET_WIFI:
                KLog.e("JK", "WIFI网络");
                if(firstNetwork){
                    indexActionsListener.requestIndex(page, limit, true);
                    indexPtrFrame.refreshComplete();
                }
                break;
            case NET_UNKNOWN:
                KLog.e("JK", "未知网络");
                break;
            default:
                KLog.e("JK", "不知道什么情况~>_<~");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        NetReceiver.ehList.remove(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_index_fragment, container, false);
        ButterKnife.bind(this, view);
//        NetReceiver.ehList.add(this);
        homeIvRight.setBackgroundResource(R.mipmap.ic_menu);
        homeIvRight.setVisibility(View.VISIBLE);
        indexActionsListener = DaggerIndexContractComponent
                .builder()
                .appComponent(CkzApplication.getAppComponent())
                .indexPresenterModule(new IndexPresenterModule(this))
                .build().getIndexPresenter();
        indexPtrFrame.setLastUpdateTimeRelateObject(this);
        indexPtrFrame.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {

                // TODO Auto-generated method stub
                if (tName == null) {
                    KLog.i("HU", "onRefreshBegin - tName == null");
                    more = false;
                    page = 1;
                    /**
                     * 网络请求数据
                     * @see IndexPresenter#requestIndex(int, int, boolean)
                     */
                    indexActionsListener.requestIndex(page, limit, false);
                    indexPtrFrame.refreshComplete();
                } else {
                    KLog.i("HU", "onRefreshBegin - tName != null");
                    more = false;
                    page = 1;
                    /**
                     * 网络请求数据
                     * @see IndexPresenter#requestIndex(int, int, boolean)
                     */
                    indexActionsListener.requestIndex(page, limit, false, tName);
                    indexPtrFrame.refreshComplete();
                }


            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                if (tName == null) {
                    KLog.i("HU", "onLoadMoreBegin - tName == null");
                    more = true;
                    ++page;
                    /**
                     * 网络请求数据
                     * @see IndexPresenter#requestIndex(int, int)
                     */
                    indexActionsListener.requestIndex(page, limit, false);
                    indexPtrFrame.refreshComplete();
                } else {
                    KLog.i("HU", "onLoadMoreBegin - tName != null");
                    more = true;
                    ++page;
                    /**
                     * 网络请求数据
                     * @see IndexPresenter#requestIndex(int, int)
                     */
                    indexActionsListener.requestIndex(page, limit, false, tName);
                    indexPtrFrame.refreshComplete();
                }


            }

        });
        // the following are default settings
        indexPtrFrame.setResistance(1.7f);
        indexPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        indexPtrFrame.setDurationToClose(200);
        indexPtrFrame.setDurationToCloseHeader(1000);
        // default is false
        indexPtrFrame.setPullToRefresh(false);
        // default is true
        indexPtrFrame.setKeepHeaderWhenRefresh(true);

        indexAdapter = new IndexAdapter(releaseInfoS);
        indexAdapter.setActivity(getActivity());
        indexAdapter.setOnItemClickListener(new OnItemClickListener<IndexBean>() {

            @Override
            public void onClick(View view, IndexBean item) {
                startActivity(new Intent(getActivity(), ShareTuiActivity.class)
                        .putExtra("id_image_url", item.getImage())
                        .putExtra("id_price", item.getPrice() + "")
                        .putExtra("id_title", item.getImage_title())
                        .putExtra("id_content", item.getSummary())
                        .putExtra("id_id", item.getId())
                        .putExtra("id_url",     item.getUrl()));
            }
        });


        indexRecyclerView.setHasFixedSize(true);//固定大小
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        indexRecyclerView.setLayoutManager(linearLayoutManager);
        //间隔线条
        indexRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        indexRecyclerView.setAdapter(indexAdapter);
        if (!NetUtils.checkNetworkInfo(getActivity())) {
            firstNetwork = true;
        }
        /**
         * 网络请求数据
         * @see IndexPresenter#requestIndex(int, int, boolean)
         */
        indexActionsListener.requestIndex(page, limit, true);
        //初始化位置监听
        LocationServerListener listener = new LocationServerListener(getActivity(), indexActionsListener);
        /**
         * @see IndexPresenter#initLocation(Context, LocationServerListener)
         */
        indexActionsListener.initLocation(getActivity(), listener);

        //接收
        rxSubscription = RxBus
                .getDefault()
                .toObservable(RefreshTypeData.class)
                .subscribe(new Action1<RefreshTypeData>() {
                    @Override
                    public void call(RefreshTypeData post) {
                        if (post.getName() != null) {
                            page = 1;//操作泽分类重新初始化值
                            more = false;//操作泽分类重新初始化值
                            KLog.i("Evd", "call - PostTypeData" + post.getName());
                            /**
                             * @see IndexPresenter#requestIndex(int, int, boolean, String)
                             */
                            indexActionsListener.requestIndex(page, limit, false, post.getName());
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        KLog.i("TAG", "call - throwable");
                    }
                });
       isPrepared = true;
        lazyLoad();
        return view;

    }


    Subscription rxSubscription;

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);//解除绑定，官方文档只对fragment做了解绑
        if (!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
    }

    //标志位，标志已经初始化完成。
    private boolean isPrepared;

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        //网络请求加载....
        KLog.e("TAG", "lazyLoad-if-I");


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        if (!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
    }
}
